package com.googlecode.animator.view.materialslibrary
{
	import com.googlecode.data.FileObjectVO;
	import com.googlecode.animator.data.Notifications;
	
	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.setTimeout;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	/**
	 * Ties in the MaterialsLibrary with the PureMVC framework. 
	 * @author USER
	 * 
	 */
	public class MaterialsLibraryMediator extends Mediator
	{
		/**
		 * Identifier. 
		 */
		public static const NAME:String = "MaterialsLibraryMediator";
		
		/**
		 * Constructor. 
		 * @param viewComponent
		 * 
		 */
		public function MaterialsLibraryMediator(viewComponent:MaterialsLibrary)
		{
			super(NAME, viewComponent);
				
		}
		
		override public function onRegister():void
		{
			viewRef.addEventListener(TileView.DELETE, onDelete);
			viewRef.addEventListener(Event.COMPLETE, onComplete);
		}
		
		override public function onRemove():void
		{
			viewRef.removeEventListener(TileView.DELETE, onDelete);
			viewRef.removeEventListener(Event.COMPLETE, onComplete);
		}
		
		/**
		 * List notification of interestes. 
		 * @return 
		 * 
		 */
		override public function listNotificationInterests():Array
		{
			var list:Array = super.listNotificationInterests();
			
			list.push(Notifications.MATERIALS_FILE_OBJECT_ADDED);
			
			return list;
		}
		
		/**
		 * Responds to notified interests. 
		 * @param notification
		 * 
		 */
		override public function handleNotification(notification:INotification):void
		{
			super.handleNotification(notification);
			
			switch(notification.getName())
			{
				case Notifications.MATERIALS_FILE_OBJECT_ADDED:
					
					handleFileObjectAdded(notification.getBody() as FileObjectVO);
					
					break;
			}
		}
		
		protected function handleFileObjectAdded(VO:FileObjectVO):void
		{
			//(viewRef.itemRenderer.newInstance() as TileView).prepare();
			viewRef.addMaterial(VO);
		}
		
		protected function onDelete(evt:Event):void
		{
			
			var name:String = (evt.target as TileView).loaderName;

			viewRef.removeMaterial(name);
			
			sendNotification(Notifications.MATERIALS_REMOVE_FILE_OBJECT, name);
		}
		
		protected function onComplete(evt:Event):void
		{
			if(evt.target is TileView)
			{
				var loader:TileView = evt.target as TileView;
				viewRef.updateMaterial(loader.loaderWidth, loader.loaderHeight, loader.loaderType, loader.loaderName);
				
			}
	
		}
		/**
		 * Returns typed reference to component. 
		 * @return 
		 * 
		 */
		protected function get viewRef():MaterialsLibrary
		{
			return viewComponent as MaterialsLibrary;
		}
	}
}